

import pygame as pg
from .. import tool
from .. import constants as c


class Menu(tool.State):
    def __init__(self):
        tool.State.__init__(self)

    def startup(self, current_time, persist):
        self.next = c.LEVEL
        self.persist = persist
        self.game_info = persist

        self.setupBackground()  # 设置背景
        self.setupOption()  # 设置选项

    def setupBackground(self):
        frame_rect = [80, 0, 800, 600]  # 背景图像的矩形区域
        self.bg_image = tool.get_image(tool.GFX[c.MAIN_MENU_IMAGE], *frame_rect)  # 获得背景图像
        self.bg_rect = self.bg_image.get_rect()
        self.bg_rect.x = 0
        self.bg_rect.y = 0

    def setupOption(self):
        self.option_frames = []  # 存储选项的帧列表
        frame_names = [c.OPTION_ADVENTURE + '_0', c.OPTION_ADVENTURE + '_1']  # 选项帧的名称列表
        frame_rect = [0, 0, 165, 77]  # 选项帧的矩形区域

        for name in frame_names:
            # 获取并添加带有缩放和颜色调整的选项帧图像
            self.option_frames.append(tool.get_image(tool.GFX[name], *frame_rect, c.BLACK, 1.7))

        self.option_frame_index = 0  # 选项帧索引
        self.option_image = self.option_frames[self.option_frame_index]  # 当前选项帧图像
        self.option_rect = self.option_image.get_rect()  # 选项帧图像的矩形区域
        self.option_rect.x = 435  # 选项帧图像的x坐标
        self.option_rect.y = 75  # 选项帧图像的y坐标

        self.option_start = 0  # 选项计时器的起始时间
        self.option_timer = 0  # 选项计时器
        self.option_clicked = False  # 记录选项是否被点击

    def checkOptionClick(self, mouse_pos):
        x, y = mouse_pos
        if (x >= self.option_rect.x and x <= self.option_rect.right and
                y >= self.option_rect.y and y <= self.option_rect.bottom):
            self.option_clicked = True  # 如果鼠标在选项上点击，则设置选项已被点击
            self.option_timer = self.option_start = self.current_time  # 重置选项计时器
        return False

    def update(self, surface, current_time, mouse_pos, mouse_click):
        self.current_time = self.game_info[c.CURRENT_TIME] = current_time

        if not self.option_clicked:
            if mouse_pos:
                self.checkOptionClick(mouse_pos)  # 检查鼠标是否点击了选项
        else:
            if (self.current_time - self.option_timer) > 200:
                self.option_frame_index += 1  # 更新选项帧索引
                if self.option_frame_index >= 2:
                    self.option_frame_index = 0
                self.option_timer = self.current_time  # 重置选项计时器
                self.option_image = self.option_frames[self.option_frame_index]  # 更新当前选项帧图像
            if (self.current_time - self.option_start) > 1300:
                self.done = True  # 如果经过一定时间，则标记菜单完成，跳转到下一个状态

        surface.blit(self.bg_image, self.bg_rect)  # 绘制背景图像
        surface.blit(self.option_image, self.option_rect)  # 绘制当前选项帧图像
